//
//  UIViewController+HKExtension.swift
//  App架构Swift
//
//  Created by 胡锦涛 on 2019/2/19.
//  Copyright © 2019 胡锦涛. All rights reserved.
//

import UIKit

//MARK:UIViewController-扩展
extension UIViewController {
    
    ///隐藏顶部导航条NavBar
    public func hk_hidenNavBar(_ animated: Bool) {
        navigationController?.setNavigationBarHidden(true, animated: animated)
        navigationController?.navigationBar.setValue(0, forKeyPath: "backgroundView.alpha")
    }
    
    ///显示顶部导航条NavBar
    public func hk_showNavBar(_ animated: Bool) {
        navigationController?.setNavigationBarHidden(false, animated: animated)
        navigationController?.navigationBar.setValue(1, forKeyPath: "backgroundView.alpha")
    }
    
    ///隐藏底部TabBar
    public func hk_hidenTabBar() {
        let tabBarController = UIApplication.shared.delegate?.window??.rootViewController as! UITabBarController
        //        tabBarController.tabBar.isHidden = true
        let frame = tabBarController.tabBar.frame
        let height = frame.size.height
        UIView.animate(withDuration: 0.35, animations: {
            tabBarController.tabBar.frame = (frame.offsetBy(dx: 0, dy: height))
        }) { (finished) in
            tabBarController.tabBar.isHidden = true
        }
    }
    
    ///显示底部TabBar
    public func hk_showTabBar() {
        let tabBarController = UIApplication.shared.delegate?.window??.rootViewController as! UITabBarController
        tabBarController.tabBar.isHidden = false
        let frame = tabBarController.tabBar.frame
        UIView.animate(withDuration: 0.35, animations: {
            tabBarController.tabBar.frame = (frame.offsetBy(dx: 0, dy: 0))
        }){ (finished) in
            
        }
    }
    
    ///返回事件
    @objc public func hk_back() {
        if let navigationController = navigationController, navigationController.viewControllers.first != self {
            navigationController.popViewController(animated: true)
        } else {
            dismiss(animated: true, completion: nil)
        }
    }
    
    ///添加子控制器
    func hk_addChildViewController(_ childVC: UIViewController, toView: UIView) {
        childVC.beginAppearanceTransition(true, animated: false)
        toView.addSubview(childVC.view)
        childVC.endAppearanceTransition()
        childVC.didMove(toParent: self)
    }
    
    ///字典转字符串
    func hk_dicValueString(_ dic: Any) -> String?{
        let data = try? JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
        let str = String(data: data!, encoding: String.Encoding.utf8)
        return str
    }
    
    ///字符串转字典
    func hk_infoFromJson(_ str: String) -> HKDefaultDic?{
        guard !str.isEmpty else {
            return HKDefaultDic()
        }
        let data = str.data(using: String.Encoding.utf8)
        if let array = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [HKDefaultDic] {
            return array!.first
        }
        return nil
    }
}

//MARK: 打印日志相关
extension UIViewController {
    
    /// 打印输出ViewController类名：
    public class func hk_logMethod(){
        hk_ChangeSel(originalSelector: #selector(UIViewController.viewWillAppear(_:)), swizzledSelector: #selector(UIViewController.hkViewWillAppear))
        hk_ChangeSel(originalSelector: #selector(UIViewController.viewWillDisappear(_:)), swizzledSelector: #selector(UIViewController.hkViewWillDisaAppear))
    }
    
    private static func hk_ChangeSel(originalSelector:Selector,swizzledSelector:Selector){
        
        let originalMethod = class_getInstanceMethod(self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
        //在进行 Swizzling 的时候,需要用 class_addMethod 先进行判断一下原有类中是否有要替换方法的实现
        let didAddMethod:Bool = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
        //如果 class_addMethod 返回 yes,说明当前类中没有要替换方法的实现,所以需要在父类中查找,这时候就用到 method_getImplemetation 去获取 class_getInstanceMethod 里面的方法实现,然后再进行 class_replaceMethod 来实现 Swizzing
        if didAddMethod {
            class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
        }else {
            method_exchangeImplementations(originalMethod!, swizzledMethod!)
        }
        
    }
    
    @objc func hkViewWillAppear(_ animated: Bool) {
        // 获取命名空间(Swift 类名格式: 主工程.类名 - ProjectName.UIViewController)
        guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
            print("没有获取命名空间")
            return
        }
        
        var className:String = NSStringFromClass(self.classForCoder)
        if className.contains(nameSpace) {
            className = className.replacingOccurrences(of: "\(nameSpace).", with: "")
        }
        HKLog("HKViewWillAppear===========\(className)")
        self.hkViewWillAppear(animated)
    }
    
    @objc func hkViewWillDisaAppear(_ animated: Bool) {
        // 获取命名空间(Swift 类名格式: 主工程.类名 - ProjectName.UIViewController)
        guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
            print("没有获取命名空间")
            return
        }
        
        var className:String = NSStringFromClass(self.classForCoder)
        if className.contains(nameSpace) {
            className = className.replacingOccurrences(of: "\(nameSpace).", with: "")
        }
        HKLog("HKViewWillDisaAppear===========\(className)")
        self.hkViewWillDisaAppear(animated)
        
    }
}
